local tongzhou = fk.CreateSkill{
  name = "sclan__tongzhou",
  tags = { Skill.Family },
}

local prompts = {}
prompts.invoke = "#sclan__tongzhou-invoke"
prompts.use = "#sclan__tongzhou-use"

Fk:loadTranslationTable{
  ["sclan__tongzhou"] = "同舟",
  [":sclan__tongzhou"] = "宗族技，当你每回合使用的首张牌结算完成后，若为红色基本牌或普通锦囊牌，你可以令一名同族角色视为使用之。",

  [prompts.invoke] = "同舟：可以令一名同族角色使用%arg",
  [prompts.use] = "同舟：使用 %arg",
}

---@param from ServerPlayer
---@param player ServerPlayer
---@return boolean
local isFamilyMember = function (from, player)
  local manbers = {"huangzu", "huangchengyan", "huangzhong", "god_huangzhong", "huanggai", "huangyueying", "huangshe"}
  if table.contains(manbers, Fk.generals[player.general].trueName) then
    return true
  end
  if player.deputyGeneral ~= "" and table.contains(manbers, Fk.generals[player.deputyGeneral].trueName) then
    return true
  end
  return player == from
end

---@return boolean
local isRedImmediate = function (card)
  return card.color == Card.Red and (card.type == Card.TypeBasic or card:isCommonTrick())
end

tongzhou:addEffect(fk.CardUseFinished, {
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(tongzhou.name) and isRedImmediate(data.card) then
      local uses = player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
        return e.data.from == player
      end, Player.HistoryTurn)

      if #uses == 1 and uses[1].data.card == data.card then
        event:setCostData(self, data.card)
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local card = event:getCostData(self) ---@type Card
    local _card = Fk:cloneCard(card.name)
    _card.skillName = tongzhou.name
    local familys = table.filter(room.alive_players, function (p)
      return isFamilyMember(player, p)
      and #_card:getAvailableTargets(p, { bypass_times = true }) > 0
    end)
    local to = room:askToChoosePlayers(player, {
      targets = familys,
      min_num = 1,
      max_num = 1,
      skill_name = tongzhou.name,
      prompt = "#sclan__tongzhou-invoke:::"..card:toLogString(),
      cancelable = true,
    })

    if #to == 1 then
      event:setCostData(self, {to[1], _card})
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local user, card = table.unpack(event:getCostData(self)) ---@type ServerPlayer, Card
    room:askToUseVirtualCard(user, {
      name = card.name,
      skill_name = tongzhou.name,
      cancelable = false,
      prompt = "#sclan__tongzhou-use:::"..card:toLogString()
    })
  end
})

return tongzhou